package com.yuncool.auth.handler;

import com.alibaba.fastjson.JSONObject;
import com.yuncool.ServiceResult;
import com.yuncool.auth.bo.UserDetailsBO;
import com.yuncool.domain.MemberInfo;
import com.yuncool.mapper.MemberInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * 自定义登陆成功处理器
 */
@Component
@Slf4j
public class AuthSuccessHandler implements AuthenticationSuccessHandler {

	@Autowired
	MemberInfoMapper memberInfoMapper;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
		UserDetailsBO user = (UserDetailsBO) authentication.getPrincipal();
		Date now = new Date();
		log.info(now + "\tUserId:" + user.getUserId() + "----login");
		MemberInfo memberInfo = new MemberInfo();
		memberInfo.setUserId(user.getUserId());
		memberInfo.setLoginTime(now);
		memberInfoMapper.updateByPrimaryKeySelective(memberInfo);
		ServiceResult<Boolean> result = new ServiceResult<>();
		result.setResultCode(String.valueOf(HttpStatus.OK.value()));
		result.setResultMsg("登陆成功!");
		result.setResultData(true);
		httpServletResponse.setContentType("application/json;charset=UTF-8");
		httpServletResponse.getWriter().write(JSONObject.toJSONString(result));
	}
}
